package com.bpzj.db.mongo.service;

import com.bpzj.db.mongo.document.Country;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.Field;
import org.springframework.data.mongodb.core.aggregation.Fields;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author bpzj 2019/8/2 10:44
 */
@Slf4j
@Component
public class CountryService {

  @Autowired
  private MongoTemplate mongoTemplate;

  public boolean insertCountry(Country country) {
    Country insert = mongoTemplate.insert(country);
    return true;
  }

  public void getPage(int pageSize, int pageNum) {
    Document queryObject = new Document();
    queryObject.put("name", "中国");
    Query query = new BasicQuery(queryObject);
    long total = mongoTemplate.count(query, Country.class);

    query.skip(pageSize * (pageNum - 1));
    query.limit(pageSize);
    List<Country> countries = mongoTemplate.find(query, Country.class);
    log.debug("查询到数据: {}", countries);

    // 组装成 page 对象

    // todo 聚合查询

    Field field = Fields.field("c", "d");
    Aggregation.newAggregation(Aggregation.project(Fields.fields("a","b").and(field)));
  }
}
